﻿using System;
using System.Web;

using OctoOS;
using OctoOS.UI;

public partial class __article : OOSPage
{
	class QueryString
	{
		[QueryStringMember]
		[IntegerBase(64)]
		internal long ID = 0;

		/// <summary>
		/// article page index
		/// </summary>
		[QueryStringMember(true)]
		internal long Page = 0;

		/// <summary>
		/// comment page index
		/// </summary>
		[QueryStringMember(true)]
		internal int Cpage = 0;

		[QueryStringMember(true)]
		[RegexValidator("^$|admin")]
		internal string Mode = string.Empty;

		[QueryStringMember(true)]
		internal string Name = "";

		//admin mode
		public bool Admin
		{
			get
			{
				return Mode.Equals("admin", StringComparison.OrdinalIgnoreCase);
			}
		}

		void PostInit()
		{
			if(Cpage > 0)
				Cpage--;
		}
	}

	QueryString _queryString;
	Page _currentPage;

	protected void Page_Init(object sender, EventArgs e)
	{
		_queryString = EnableQueryString<QueryString>();
	}

	protected void Page_Load(object sender, EventArgs e)
	{
		AddBreadcrumb(string.Empty, "/");
		var settings = AppUtil.GetSettings(OOSRequest.Current);
		Article article = ApiService.GetArticle(OOSRequest.Current, _queryString.ID);

		//проверка на владельца статьи или администратора
		if(_queryString.Admin)
		{
			if(!OOSRequest.Current.IsModerator &&
				article.UserID != OOSRequest.Current.UserID)
			{
				//не модератор и не создатель статьи не могут входить по этим модом
				throw new HttpException();
			}
			else
			{
				if(!article.PublishedNow)
				{
					noPublishedMsg.Visible = true;
					noPublishedMsg.SetContent(Resources.Main.article_NotPublishedMsg);
					postForm.Visible = false;
				}

				adminMode.Visible = true;
				adminMode.SetContent(Resources.Main.article_AdminMode);
			}
		}
		else
		{
			if(!article.PublishedNow)
				throw new HttpException(404, "Article Not Published");
		}

		//redirect if article name is incorrect
		if(!String.Equals(
			Urls.GetEncodedName(article.Title), _queryString.Name, StringComparison.OrdinalIgnoreCase))
		{
			Response.RedirectPermanent(
				Urls.GetArticle(_queryString.ID, _queryString.Admin, false, article.Title));
		}

#warning почему модератор?
		if(OOSRequest.Current.IsModerator)
		{
			edit.HRef = Urls.GetEditArticle(_queryString.ID);
			bookmarkButton.Visible = settings.Bookmarks;
			shareBtn.Visible = settings.SendToFriend;
			printButton.Visible = settings.Print;
			//trackbackButton.Visible = resource.TrackbarUrl;
			rssButton.Visible = settings.CommentRss;
		}
		else
		{
			//отображение комментариев
			if(settings.CommentsEnabled == CommentsEnabled.Disabled)
			{
				postForm.Visible = false;
				threadView.Visible = false;
			}
			else
			{
				//не истекло ли время комментирования
				if(settings.DisableAfter > 0
					&& (article.PublishStartTime - DateTime.UtcNow).Days > settings.DisableAfter)
				{
					postForm.Visible = false;
				}

				if(settings.CommentsEnabled == CommentsEnabled.Registered)
					postForm.Visible = OOSRequest.Current.IsAuthenticated;
			}
		}

		postForm.ThreadID = _queryString.ID;
		PageTitle = article.Title;
		MetaDescription = article.Preface;
		articleTime.DateTime = article.PublishStartTime.ToLocalTime();
		articleAuthor.Text = " " + Resources.Main.article_Author + " " + article.Author;

		var allPages = article.GetPages(_queryString.Admin);
		if(allPages.Length != 0)
		{
			//если выбрана 1 страница комментариев то отображаем полную статью, если нет - то только превью
			if(_queryString.Cpage == 0)
			{
				articleView.SetActiveView(regularView);

#warning нужно ли высчитывать айди первой страницы или передавать его в юрлы
				long pageID = _queryString.Page == 0 ? article.GetFirstPageID(_queryString.Admin) : _queryString.Page;

				for(int i = 0; i < allPages.Length; i++)
				{
					var p = allPages[i];

					if(p.ID == pageID)
					{
						_currentPage = p;
						pager.SelectedIndex = i;
					}

					pager.AddPage((i + 1).ToString(),
								  Urls.GetArticle(
									_queryString.ID, _queryString.Admin, false, p.ID, article.Title));
				}

				if(_currentPage == null)
					throw new HttpException(404, "Page Not Found");

				pageName.InnerText = _currentPage.Title;

				foreach(var section in _currentPage.Sections)
				{
					var cc = new ContletControl()
								{
									ID = "s" + section.ID,
									EntityID = _queryString.ID,
									ContletID = section.ID,
									DeleteUrl = Urls.GetDeleteSection(article.ID, pageID, section.ID)
								};

					cc.Items.Add(new ContletHeaderRenderer());

					cc.Items.Add(new BasicEditor()
						{
							TitleCaption = Resources.Main.article_SectionTitle,
							BodyCaption = Resources.Main.article_SectionText
						});

					sectionsDiv.Controls.Add(cc);
				}
			}
			else
			{
				articleView.SetActiveView(shortView);
				preface.Text = article.Preface;
				articleUrl.HRef = Urls.GetArticle(_queryString.ID, _queryString.Admin, true, article.Title);
				//commentsHeader.InnerText += String.Format(" (page {0})", _queryString.cpage + 1);
			}
		}

		threadView.GroupID = OOSRequest.Current.ResourceID;
		threadView.EntityID = _queryString.ID;
		threadView.PageUrlPattern = Urls.GetArticle(_queryString.ID, _queryString.Admin, false, article.Title) + "&cpage={0}";
		threadView.FirstPageUrl = Urls.GetArticle(_queryString.ID, _queryString.Admin, false, article.Title);
		threadView.PageIndex = _queryString.Cpage;
	}

	//protected void SubmitPost(object sender, EventArgs e)
	//{
	//    if(IsValid)
	//    {
	//        ApiService.AddPost(OOSRequest.Current, threadView.ThreadID,
	//                OOSRequest.Current.RequestID, 0, postForm.Message, postForm.Author);

	//        Response.Redirect(Urls.GetPostRedirectUrl(_queryString.ID,
	//            OOSRequest.Current.RequestID));
	//    }
	//}
}